package com.jing.ads.handler;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.jing.ads.application.MyApplication;
import com.jing.ads.model.Entry;
import com.jing.ads.model.PushAppInfo;
import com.jing.ads.model.PushAppInfo.AppDetail;

public class GetAppsHandler extends BaseHandler {

	private String udid = "";
	private PushAppInfo info = null;
	
	public GetAppsHandler(Context context) {
		super(context);
		MyApplication app = (MyApplication) context.getApplicationContext();
		udid = app.getUDID();
		info = new PushAppInfo();
		this.action = "getapps";
	}
	
	@Override
	protected void initRequest() {
		this.params.put("udid", udid);
		this.params.put("version", String.valueOf(versionCode));
	}

	@Override
	protected void initEntity() {
		
	}

	@Override
	protected void onParser(JSONObject response) {
		if (response == null) {
			return;
		}
		String errorCode = response.optString("error_code", "");
		info.setErrorCode(errorCode);
		String bu = response.optString("base_path", "");
		info.setBaseUrl(bu);
		ArrayList<AppDetail> list = info.getAppsList();
		JSONArray ja = response.optJSONArray("apps");
		if (!JSONObject.NULL.equals(ja)) {
			int size = ja.length();
			for (int i = 0; i < size; i++) {
				JSONObject jo = ja.optJSONObject(i);
				if (!JSONObject.NULL.equals(jo)) {
					AppDetail app = new AppDetail();
					app.appId = jo.optString("appid", "");
					app.iconUrl = bu + jo.optString("icon_path", "");
					app.appName = jo.optString("name", "");
					app.downloadUrl = bu + jo.optString("apk_path", "");
					app.size = Integer.valueOf(jo.optString("apk_size", ""));
					app.packageName = jo.optString("package_name", "");
					app.downloadCount = 0;
					app.downloadStatus = AppDetail.UNDOWNLOAD;
					list.add(app);
				}
			}
		}
	}

	@Override
	public Entry getData() {
		return info;
	}

}
